<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小组名称" prop="teamName">
            <el-input v-model="formData.teamName" placeholder="请输入小组名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小组编号" prop="teamCode">
            <el-input v-model="formData.teamCode" placeholder="请输入小组编号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小组经理" prop="managerId">
<!--            <el-input v-model="formData.managerId" placeholder="请输入小组经理" />-->
            <el-select v-model="formData.managerId" clearable placeholder="请选择小组经理">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
         </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="departmentId">
<!--            <el-input v-model="formData.departmentId" placeholder="请输入所属部门" />-->
            <el-tree-select
              v-model="formData.departmentId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择归属部门"
            />
          </el-form-item>
         </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售目标金额" prop="teamGoal">
            <el-input v-model="formData.teamGoal" placeholder="请输入小组销售目标金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小组成立日期" prop="establishmentDate">
            <el-date-picker style="width: 100%"
              v-model="formData.establishmentDate"
              type="date"
              value-format="x"
              placeholder="选择小组成立日期"
            />
          </el-form-item>
          </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小组状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio value="1">活跃</el-radio>
              <el-radio value="0">已解散</el-radio>
            </el-radio-group>
          </el-form-item>
         </el-col>
        <el-col :span="12">
          <el-form-item label="销售区域" prop="region">
            <el-input v-model="formData.region" placeholder="请输入负责销售区域" />
          </el-form-item>
          </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售产品类别" prop="productFocus">
            <el-input v-model="formData.productFocus" placeholder="请输入销售产品类别" />
          </el-form-item>
          </el-col>
        <el-col :span="12">
          <el-form-item label="合作模式" prop="contractType">
            <el-select v-model="formData.contractType" placeholder="请选择合作模式">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_SALES_CONTRACT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小组描述信息" prop="teamDescription">
            <el-input type="textarea" v-model="formData.teamDescription" placeholder="请输入小组描述信息" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName">
        <el-tab-pane label="组员信息" name="teamItemForm">
          <TeamItemForm ref="teamItemFormRef" :team-id="formData.teamId" :team-msg="formData.users" />
        </el-tab-pane>
      </el-tabs>

<!--      <el-form-item label="本季度销售目标" prop="currentQuarterTarget">-->
<!--        <el-input v-model="formData.currentQuarterTarget" placeholder="请输入本季度销售目标" />-->
<!--      </el-form-item>-->

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { BizSalesTeamApi, BizSalesTeam } from '@/api/biz/salesteam'
import TeamItemForm from './components/TeamItemForm.vue'
const subTabsName = ref('teamItemForm')
/** 销售团队信息 表单 */
defineOptions({ name: 'BizSalesTeamForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList = ref<Tree[]>([]) // 树形结构
import { defaultProps, handleTree } from '@/utils/tree'
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
import * as DeptApi from "@/api/system/dept";
import * as UserApi from "@/api/system/user";
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  teamId: undefined,
  teamName: undefined,
  teamCode: undefined,
  managerId: undefined,
  departmentId: undefined,
  teamGoal: undefined,
  currentQuarterTarget: undefined,
  teamDescription: undefined,
  establishmentDate: undefined,
  status: undefined,
  region: undefined,
  productFocus: undefined,
})
const formRules = reactive({
  teamName: [{ required: true, message: '小组名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogTitle.value = t('action.' + type)
  formType.value = type
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = await UserApi.getSimpleUserList()
  resetForm()
  // 修改时，设置数据
  console.info(id)
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BizSalesTeamApi.getBizSalesTeam(id)
    } finally {
      formLoading.value = false
    }
  }
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const teamItemFormRef = ref()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BizSalesTeam
    // 拼接子表的数据
    data.items = teamItemFormRef.value.getData()
    if (formType.value === 'create') {
      await BizSalesTeamApi.createBizSalesTeam(data)
      message.success(t('common.createSuccess'))
    } else {
      await BizSalesTeamApi.updateBizSalesTeam(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    teamId: undefined,
    teamName: undefined,
    teamCode: undefined,
    managerId: undefined,
    departmentId: undefined,
    teamGoal: undefined,
    currentQuarterTarget: undefined,
    teamDescription: undefined,
    establishmentDate: undefined,
    status: undefined,
    region: undefined,
    productFocus: undefined,
  }
  formRef.value?.resetFields()
}
</script>
